package com.zs.zcerp.entrance.init;

import com.alibaba.fastjson.JSON;
import com.zs.zcerp.entrance.entity.*;
import com.zs.zcerp.entrance.service.*;
import com.zs.zcerp.remark.service.CommonService;
import com.zs.zcerp.system.entity.User;
import com.zs.zcerp.system.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 初始化所有部门、职位和职员的信息
 */
//@Component
public class InitEntranceData implements ApplicationRunner {

    private final static Logger logger = LoggerFactory.getLogger(InitEntranceData.class);

    final static SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IDpDeptService dpDeptService;

    @Autowired
    private IEpMainService epMainService;

    @Autowired
    private IPostService postService;

    @Autowired
    private ISyorgService syorgService;

    @Autowired
    private IEntranceAccessService eac;

    @Autowired
    private CommonService commonService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IEpPhotoService epPhotoService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info(df.format(new Date()) + "开始初始化数据...");

        final Base64.Encoder encoder = Base64.getEncoder();
        // 查询数据库中所有公司, 开始初始化所有公司
        List<Syorg> syorgList = syorgService.listSyorgs();
        for (Syorg syorg : syorgList) {
            try {
                eac.CreateOrUpdateSyorg(syorg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 查询数据库中所有部门, 开始初始化所有部门
        List<DpDept> dpDeptList = dpDeptService.listDpDepts();
        // 记录父部门还未插入的部门,最后再更新
        List<DpDept> errDpDepts = new ArrayList<>();
        for (DpDept dpDept : dpDeptList) {
            try {
                eac.CreateOrUpdateDpDept(dpDept);
            } catch (Exception e) {
                errDpDepts.add(dpDept);
                e.printStackTrace();
            }
        }

        // 再次尝试创建刚刚父部门不存在的部门
        for (DpDept dpDept : errDpDepts) {
            logger.info("再次尝试创建部门" + JSON.toJSONString(dpDept));
            try {
                eac.CreateOrUpdateDpDept(dpDept);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 查询所有职位, 开始初始化所有职位
        List<Post> postList = postService.listPosts();
        for (Post post : postList) {
            try {
                eac.CreateOrUpdatePost(post);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 查询所有员工, 开发初始化所有员工
        List<EpMain> epMainList = epMainService.listEpMains();
        for (EpMain epMain : epMainList) {
            try {
                // epMain添加照片信息
                EpPhoto epPhoto = epPhotoService.findByEmpNo(epMain.getEmpCode());

                if (epPhoto != null && epPhoto.getPhoto1() != null) {
                    epMain.setPhoto(encoder.encodeToString(epPhoto.getPhoto1()));
                }
                // 更新门禁用户信息
                eac.CreateOrUpdateEmp(epMain);
            } catch (Exception e) {
                logger.error(e.getMessage() + "更新门禁系统用户出错");
            }

            // 更新本系统的user信息
            User user = new User();
            try {
                // 查询用户是否已存在
                User user0 = userService.findByName(epMain.getEmpCode());

                user.setUsername(epMain.getEmpCode());
                user.setCname(epMain.getName());

                try {
                    user.setCname(commonService.findEmpnameByNo(epMain.getOrgId(), epMain.getEmpId(), "T"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                user.setMobile(epMain.getMobile());
                user.setRoleId("84");
                user.setSex("2");
                if ("M".equals(epMain.getGender())) {
                    user.setSex("0");
                } else if ("F".equals(epMain.getGender())) {
                    user.setSex("1");
                }
                if (user0 != null) {
                    user.setRoleId(user0.getRoleId());
                    if ("1".equals(epMain.getEmpState()) || "3".equals(epMain.getEmpState()) || "5".equals(epMain.getEmpState())) {
                        user.setStatus("1");
                    } else {
                        user.setStatus("0");
                    }
                    // 更新用户
                    userService.updateUser(user);
                } else {
                    // 创建用户
                    userService.createUser(user);
                }
            } catch (Exception e) {
                logger.error(e.getMessage() + "新增vitoryERP用户出错" + JSON.toJSONString(user));
            }
        }

        logger.info(df.format(new Date()) + "初始化数据完成");
    }
}

